package com.lisp.springframework.tx.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lisp.springframework.tx.model.Foo;

@Repository
public class JdbcTemplateDaoImpl implements JdbcTemplateDao {

    private static final FooMapper FOO_MAPPER = new FooMapper();
    
    private JdbcTemplate jdbcTemplate;
    
    public JdbcTemplateDaoImpl(DataSource ds) {
        this.jdbcTemplate = new JdbcTemplate(ds);
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Foo find(long id) {
        return jdbcTemplate.queryForObject(
                "select * from foo where id=?", FOO_MAPPER, id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void insert(Foo foo) {
        jdbcTemplate.update("insert into foo(id, work_id, update_date) values (?,?,?)",
                foo.getId(), foo.getWorkId(), foo.getUpdateDate());
    }
    
    private static final class FooMapper implements RowMapper<Foo> {
        
        @Override
        public Foo mapRow(ResultSet rs, int rowNum) throws SQLException {
            Foo ret = new Foo();
            ret.setId(rs.getLong("id"));
            ret.setWorkId(rs.getInt("work_id"));
            ret.setUpdateDate(rs.getDate("update_date"));
            return ret;
        }
    }

    @Override
    public List<Foo> findByIdIn(List<Long> ids) {
        return null;
        //return jdbcTemplate.query("select * from foo where id in (?)", FOO_MAPPER, ids);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void update(Foo foo) {
        jdbcTemplate.update("update foo set work_id=?, update_date=? where id=?", 
                foo.getWorkId(), foo.getUpdateDate(), foo.getId());
    }

}
